/**
 * 工具类 - 提供各种实用函数
 */

export default {

	/**
	 * scene解码
	 */
	scene_decode(e) {
		if (e === undefined)
			return {};
		let scene = decodeURIComponent(e),
			params = scene.split(','),
			data = {};
		for (let i in params) {
			var val = params[i].split(':');
			val.length > 0 && val[0] && (data[val[0]] = val[1] || null)
		}
		return data;
	},

	/**
	 * 格式化日期格式 (用于兼容ios Date对象)
	 */
	format_date(time) {
		// 将xxxx-xx-xx的时间格式，转换为 xxxx/xx/xx的格式 
		return time.replace(/\-/g, "/");
	},

	/**
	 * 对象转URL
	 */
	urlEncode(data) {
		var _result = [];
		for (var key in data) {
			var value = data[key];
			if (value.constructor == Array) {
				value.forEach(_value => {
					_result.push(key + "=" + _value);
				});
			} else {
				_result.push(key + '=' + value);
			}
		}
		return _result.join('&');
	},

	/**
	 * 遍历对象
	 */
	objForEach(obj, callback) {
		Object.keys(obj).forEach((key) => {
			callback(obj[key], key);
		});
	},

	/**
	 * 是否在数组内
	 */
	inArray(search, array) {
		for (var i in array) {
			if (array[i] == search) {
				return true;
			}
		}
		return false;
	},

	/**
	 * 深度克隆对象
	 */
	deepClone(obj) {
		if (obj === null || typeof obj !== 'object') {
			return obj;
		}
		if (obj instanceof Date) {
			return new Date(obj.getTime());
		}
		if (obj instanceof Array) {
			return obj.map(item => this.deepClone(item));
		}
		if (typeof obj === 'object') {
			var clonedObj = {};
			for (var key in obj) {
				if (obj.hasOwnProperty(key)) {
					clonedObj[key] = this.deepClone(obj[key]);
				}
			}
			return clonedObj;
		}
	},

	/**
	 * 判断是否为正整数
	 */
	isPositiveInteger(value) {
		return /(^[0-9]\d*$)/.test(value);
	},

	/**
	 * 防抖函数
	 */
	debounce(fn, delay = 300) {
		let timer = null;
		return function() {
			const context = this;
			const args = arguments;
			clearTimeout(timer);
			timer = setTimeout(function() {
				fn.apply(context, args);
			}, delay);
		};
	},

	/**
	 * 节流函数
	 */
	throttle(fn, delay = 300) {
		let lastTime = 0;
		return function() {
			const currentTime = Date.now();
			const context = this;
			const args = arguments;
			if (currentTime - lastTime > delay) {
				fn.apply(context, args);
				lastTime = currentTime;
			}
		};
	},


	/**
	 * 对Date的扩展，将 Date 转化为指定格式的String
	 * 月(Y)、月(m)、日(d)、小时(H)、分(M)、秒(S) 可以用 1-2 个占位符，
	 * 例子：
	 * dateFormat('YYYY-mm-dd HH:MM:SS', new Date()) ==> 2020-01-01 08:00:00
	 */
	dateFormat(fmt, date) {
		const opt = {
			"Y+": date.getFullYear().toString(), // 年
			"m+": (date.getMonth() + 1).toString(), // 月
			"d+": date.getDate().toString(), // 日
			"H+": date.getHours().toString(), // 时
			"M+": date.getMinutes().toString(), // 分
			"S+": date.getSeconds().toString() // 秒
			// 有其他格式化字符需求可以继续添加，必须转化成字符串
		};
		let ret;
		for (let k in opt) {
			ret = new RegExp("(" + k + ")").exec(fmt);
			if (ret) {
				fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
			};
		};
		return fmt;
	},

	/**
	 * 获取设备信息
	 */	
	getDeviceInfo() {
		try {
			return uni.getSystemInfoSync();
		} catch (e) {
			console.error('获取设备信息失败', e);
			return {};
		}
	},
	duration(r) {
		var t = 0, e = 0;
		(r = Math.ceil(r)) > 60 && (t = parseInt(r / 60), r = parseInt(r % 60), t > 60 && (e = parseInt(t / 60), 
		t = parseInt(t % 60)));
		var n = "";
		return n += parseInt(r) + "秒", 0 != t && (n = parseInt(t) + "分" + n), e > 0 && (n = parseInt(e) + "小时" + n), 
		n;
	},

	/**
	 * 格式化时长为HH:MM:SS格式
	 */
	formatTime(seconds) {
		seconds = Math.floor(seconds);
		const hours = Math.floor(seconds / 3600);
		const minutes = Math.floor((seconds % 3600) / 60);
		const remainingSeconds = seconds % 60;
		
		return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
	},
	kb(r) {
		if (r / 1024 >= 1024) return (t = (r - r % 1024) / 1024 / 1024).toFixed(2) + "M";
		var t = (r - r % 1024) / 1024;
		return t.toFixed(2) + "KB";
	},

	/**
	 * 更详细的文件大小格式化
	 */
	formatFileSize(bytes) {
		if (bytes === 0) return '0 Bytes';
		
		const k = 1024;
		const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
		const i = Math.floor(Math.log(bytes) / Math.log(k));
		
		return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
	},

	/**
	 * 生成唯一ID
	 */
	generateUUID() {
		return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
			const r = Math.random() * 16 | 0;
			const v = c === 'x' ? r : (r & 0x3 | 0x8);
			return v.toString(16);
		});
	},
	handleUrl(str) {
	  var reg = /(https?|http|ftp|file):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]/g;
	  str = str.match(reg);
	  if (str) {
	    return (str[0])
	  } else {
	    return (false)
	  }
	},

	/**
	 * 复制文本到剪贴板
	 */
	copyToClipboard(text) {
		return new Promise((resolve, reject) => {
			uni.setClipboardData({
				 data: text,
				 success: function () {
					 resolve();
				 },
				 fail: function (err) {
					 reject(err);
				 }
			});
		});
	},

	/**
	 * 显示加载提示
	 */
	showLoading(title = '加载中') {
		return new Promise((resolve) => {
			uni.showLoading({
				title: title,
				mask: true,
				success: resolve
			});
		});
	},

	/**
	 * 隐藏加载提示
	 */
	hideLoading() {
		uni.hideLoading();
	},

	/**
	 * 显示Toast提示
	 */
	showToast(title, icon = 'none', duration = 2000) {
		return new Promise((resolve) => {
			uni.showToast({
				title: title,
				icon: icon,
				duration: duration,
				success: resolve
			});
		});
	}
};
